const fs = require('fs')
const csv = require('csvtojson')
const iconv = require('iconv-lite');
const { resolve } = require('path');
const dirCache={};


var doneWriting = false;
var count = 1

var writeData =
[
  {
    plc: 'PLC_1',
    value: '40',
    address: 'DB100,Real12',
    factory: '1.5'
  }
]
// let filePath = __dirname + "\\" + "trend" + "\\" + fileFormatDate(new Date())  + "\\" + writeData[0].address + ".csv"

let header = 'plc, value, time \n';

// var dataCSV = [];
// var dataSearchData = [];



// exports.getTrendData = function(tag,start,end){

//   dataCSV = [];
//   dataSearchData = []

//   console.log(`tag:${tag},start:${start},end:${end}`)

//   var tempStart = start.slice(0,10)
//   var tempEnd = end.slice(0,10)
//   var prefix = "./trend/"
//   var suffix = "/" + tag + ".csv"
//   var filePath = getAllDate(tempStart,tempEnd,prefix,suffix)

//   console.log(filePath)

//   f(filePath)

//   // console.log("-----------------",result)

// }

// async function getFileData(filePath){
//   const converter = await csv()
//   .fromFile(filePath,{encoding:'binary'})
//   .then((json) => {
//     var buf =  Buffer(JSON.stringify(json), 'binary');
//     var str = iconv.decode(buf, 'GBK');
//     str=JSON.parse(JSON.stringify(str))
//     var result =eval(str)
//     // console.log(result)
//     dataCSV.push(str)
//   })
// }

// async function f(filePath) {

//   // filePath = [
//   //   './trend/20240816/DB100,Real0.csv',
//   //   './trend/20240817/DB100,Real0.csv'
//   // ]


//   for (const e of filePath) {
//     const res = await getFileData(e)
//   }


//   for  (var e of dataCSV) {

//     var  data = eval(e)

//     // console.log("***",data)


//     for  (const e of data) {

//       // console.log("+++",e)

//       dataSearchData.push(e)

//     }

//     // console.log(dataSearchData)
//   }

//   console.log(dataSearchData)



// }

function searchDataByDate(dates,tag){


  // dates.forEach( date => {

    var filePath ='./trend'  + "//" + dates[0]  + "//" + tag + ".csv"

    var result = writeCSVData(filePath)

    console.log(`result-----------------: ${result}`)

  // });


}


function writeCSVData(filePath){
  var result
  const converter = csv().fromFile(filePath,{encoding:'binary'})
  converter.then((json) => {
    //binary和fromFile中的文件读取方式要一致
    var buf =  Buffer(JSON.stringify(json), 'binary');//第一个参数格式是字符串
    var str = iconv.decode(buf, 'GBK');//原文编码我这是GBK
    str=JSON.parse(JSON.stringify(str))//解码后为字符串，需要先转成json字符串
    result =eval(str)

  })
  setTimeout(() => {
    return result
  },1000)
}

//获取时间区间所有日期
function getAllDate(start,end,prefix,suffix){
  let dateArr = []
  let startArr = start.split('-')
  let endArr = end.split('-')
  let db = new Date()
  db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2])
  let de = new Date()
  de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2])
  let unixDb = db.getTime()
  let unixDe = de.getTime()
  let stamp
  const oneDay = 24 * 60 * 60 * 1000;
  for (stamp = unixDb; stamp <= unixDe;) {
  dateArr.push(prefix + fileFormatDate(new Date(parseInt(stamp))) + suffix)
  stamp = stamp + oneDay
  }
  return dateArr
}

//2\filter data
exports.recordData = function(result,conn){
  //1.add item to plc

  //only add  one times item
  if (count < 2 ){
    result.forEach(e => {
      // console.log(e.address)
      conn.addItems(e.address)
    });
    count += 1
  }
  //2.call function
  conn.readAllItems((anythingBad, values) => {
    if (anythingBad) { console.log("SOMETHING WENT WRONG READING VALUES!!!!"); }

    //1.replace data : value
    for (var i=0;i<result.length;i++){
      //update value
      result[i].value = values[result[i].address].toFixed(2)
      // console.log(`get plc node: ${result[i].address}, value: ${values[result[i].address]}`)
    }

    // console.log(result)

    // console.log(result)
    // console.log("--values-->>",result)

    writeToCSV(result)

    doneReading = true;
    if (doneWriting) { process.exit(); }
  });

}


//3\read plc data
//4\write csv
function writeToCSV(result){

result.forEach(e => {
  let filePath ='./trend'  + "//" + fileFormatDate(new Date())  + "//" + e.address + ".csv"
  writeFile(filePath,e);
  // console.log(filePath)
  // console.log(e)
});

}
function formatDate2FileDate(date){
  return date.slice(0,4) + date.slice(5,7) + date.slice(8,10)
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  const hours = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);
  const seconds = ('0' + date.getSeconds()).slice(-2);
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


function fileFormatDate(date) {
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  return `${year}${month}${day}`;
}


function writeFile(filePath,writeData){
  var tempData = writeData.plc + "," + writeData.value + "," + formatDate(new Date())
    if (fs.existsSync(filePath)) {
        // console.log('该路径已存在');
          // console.log("写操作")
          const converter = csv()
          .fromFile(filePath,{encoding:'binary'})
          .then((json) => {
            //binary和fromFile中的文件读取方式要一致
            var buf =  Buffer(JSON.stringify(json), 'binary');//第一个参数格式是字符串
            var str = iconv.decode(buf, 'GBK');//原文编码我这是GBK
            str=JSON.parse(JSON.stringify(str))//解码后为字符串，需要先转成json字符串
            var data=eval(str)
            // console.log(data[data.length - 1])

            //验证不为空
            if(Array.isArray(data) && data.length){

              var lastValue = data[data.length - 1].value
              var currentValue = writeData.value

              // console.log(`lastValue= ${lastValue},  currentValue=${currentValue}`)

              //compare factory
              var posValue =  Math.abs(lastValue - currentValue)
              var negValue =  (currentValue - lastValue) * -1

              var posFactory = writeData.factory * 1
              var negFactory = writeData.factory * -1

              // console.log(`posValue : ${posValue}, negValue : ${negValue},`)
              // console.log(`posFactory : ${posFactory}, negFactory : ${negFactory},`)
              // console.log(`posValue >  posFactory : ${posValue >  posFactory}`)
              // console.log(`negValue <  negFactory : ${negValue <  negFactory}`)

              if((posValue >  posFactory | negValue <  negFactory) & currentValue != 'BAD 255'){

                // console.log(`start record current value : ${writeData.value}`)

                //写入数据
                var data =  tempData +  "\n" ;
                fs.appendFile(filePath,data,'utf8',function(err){
                    if(err)  {
                        console.log(err);
                    } else {
                        // console.warn(`[${formatDate(new Date())}] ${data} update.`)
                    }
                })

              }
            }
            //为空直接写数据
            else{
                //写入数据
                var data =  tempData +  "\n" ;
                fs.appendFile(filePath,data,'utf8',function(err){
                    if(err)  {
                        console.log(err);
                    } else {
                        console.log('写入数据成功了')
                    }
                })
            }
          })


    }else{
        console.log('该路径不存在');
        console.error(filePath)
        mkdir(filePath);
        //创建header
        var data = header;
        console.error(data)
        fs.appendFile(filePath,data,'utf8',function(err){
            if(err)  {
                console.log(err);
            } else {
                console.log('appendFile 成功了')
            }
        })
    }

}

function mkdir(filePath) {
  const arr=filePath.split('/');
  let dir=arr[0];
  for(let i=1;i<arr.length;i++){
      if(!dirCache[dir]&&!fs.existsSync(dir)){
          dirCache[dir]=true;
          fs.mkdirSync(dir);
      }
      dir=dir+'/'+arr[i];
  }
  fs.writeFileSync(filePath, '')
}

